package com.ruike.alisurface.ui.settings;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.TextView;

import com.ruike.alisurface.Constant;
import com.ruike.alisurface.R;
import com.ruike.alisurface.base.BaseAty;
import com.ruike.alisurface.https.ShopApiHttp;
import com.ruike.alisurface.printer.OrderTicketBean;
import com.ruike.alisurface.printer.PrinterOperateUtils;
import com.ruike.alisurface.serialport.MsgEventBus;
import com.ruike.alisurface.serialport.QrCodeUtils;
import com.ruike.alisurface.utils.CountTimeUtils;
import com.ruike.alisurface.utils.ShareKey;
import com.voodoo.lib_http.ApiListener;
import com.voodoo.lib_logcat.L;
import com.voodoo.lib_utils.SharedUtils;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class BaseSetting_Aty extends BaseAty {

    @BindView(R.id.base_buyQuantity_et)
    EditText baseBuyQuantityEt;
    @BindView(R.id.base_buyQuantitySave_btn)
    Button baseBuyQuantitySaveBtn;
    @BindView(R.id.base_showAdv_swch)
    Switch baseShowAdvSwch;
    @BindView(R.id.base_showprinter_swch)
    Switch baseShowprinterSwch;
    boolean isprinter;
    @BindView(R.id.bt_printreceipt)
    Button btPrintreceipt;
    @BindView(R.id.bt_qrcode)
    Button btQrcode;
    @BindView(R.id.bt_qrcode_text)
    TextView btQrcodeText;
    @BindView(R.id.base_showalipay_swch)
    Switch baseShowalipaySwch;
    @BindView(R.id.base_out_time_et)
    EditText baseOutTimeEt;


    @Override
    protected int getLayoutResId() {
        return R.layout.app_base_setting;
    }

    @Override
    protected void initViews() {
        initTitleBar(false);


    }

    boolean isface;

    @Override
    protected void initData() {
        int buynumber = SharedUtils.getInstance().getInt(ShareKey.PURCHASE_COUNT, 3); // 购买数量
        baseBuyQuantityEt.setText(buynumber + "");
        int advType = SharedUtils.getInstance().getInt(Constant.AdvType.ADV_TYPE_KEY);
        if (advType == 2) {
            baseShowAdvSwch.setChecked(false);
        } else {
            baseShowAdvSwch.setChecked(true);
        }

        isprinter = SharedUtils.getInstance().getBoolean(ShareKey.IS_PRINTER);
        baseShowprinterSwch.setChecked(isprinter);
        btPrintreceipt.setVisibility(isprinter ? View.VISIBLE : View.GONE);

        isface = SharedUtils.getInstance().getBoolean(ShareKey.IS_OPEN_ALIPAY_PAY, false);
        baseShowalipaySwch.setChecked(isface);

        int baseOutTime = SharedUtils.getInstance().getInt(ShareKey.ResultOutTime, 10); // 超时时间

        baseOutTimeEt.setText(baseOutTime + "");
    }

    @OnClick({R.id.goback_imgv, R.id.base_buyQuantitySave_btn, R.id.base_showAdv_swch,
            R.id.base_showprinter_swch, R.id.base_bout_time_Save_btn,
            R.id.bt_printreceipt, R.id.bt_qrcode, R.id.base_showalipay_swch})
    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.goback_imgv:
                finish();
                break;
            case R.id.base_bout_time_Save_btn:
                String baseOutTimeEtStr = baseOutTimeEt.getText().toString().trim();
                if (!baseOutTimeEtStr.isEmpty()) {
                    int OutTimeEtStr = Integer.parseInt(baseOutTimeEtStr);
                    if (OutTimeEtStr > 0) {
                        if (OutTimeEtStr > 20) {
                            showErrorToast("倒计时时间不能超过20");
                            return;
                        }
                        showRightToast("设置成功");
                        SharedUtils.getInstance().putInt(ShareKey.ResultOutTime, OutTimeEtStr); // 超时时间
                    } else {
                        showErrorToast("倒计时时间不能为零");
                    }
                } else {
                    showErrorToast("倒计时时间不能为空");
                }
                break;

            case R.id.base_buyQuantitySave_btn:
                String buyQuantityStr = baseBuyQuantityEt.getText().toString().trim();
                if (!buyQuantityStr.isEmpty()) {
                    int buyQuantity = Integer.parseInt(buyQuantityStr);
                    if (buyQuantity > 0) {
                        if (buyQuantity > 12) {
                            showErrorToast("购买数量不能超过12");
                            return;
                        }
                        showRightToast("设置成功");
                        setCount(buyQuantityStr);
                    } else {
                        showErrorToast("购买数量不能为零");
                    }
                } else {
                    showErrorToast("购买数量不能为空");
                }
                break;

            case R.id.base_showAdv_swch:
                SharedUtils.getInstance().putInt(Constant.AdvType.ADV_TYPE_KEY, baseShowAdvSwch.isChecked()
                        ? Constant.AdvType.IMAVE : Constant.AdvType.NONE); // 选中的话为轮播图广告，关闭的话状态为2

                showRightToast("设置成功");
                break;
            case R.id.base_showprinter_swch:
                isprinter = !isprinter;
                SharedUtils.getInstance().putBoolean(ShareKey.IS_PRINTER, isprinter);
                showRightToast("设置成功");
                btPrintreceipt.setVisibility(isprinter ? View.VISIBLE : View.GONE);
                break;
            case R.id.bt_printreceipt:

                showRightToast("开始打印小票");
                setPrinter();
//
                break;
            case R.id.bt_qrcode:

                showRightToast("点击了反扫");
                QrCodeUtils.sendCommandCode();

                break;

            case R.id.base_showalipay_swch:

                isface = !isface;
                SharedUtils.getInstance().putBoolean(ShareKey.IS_OPEN_ALIPAY_PAY, isface);

                break;
        }
    }

    public void setPrinter() {
        PrinterOperateUtils.getInstance().connectUsbPrinter(this);
        new CountTimeUtils(2) {
            @Override
            public void onTick(long mMillisUntilFinished) {

            }

            @Override
            public void onFinish() {
                if (!PrinterOperateUtils.getInstance().isConnected()) {
                    L.i("没有连接成功");
                    showErrorLongToast("打印小票没有连接成功", 5000);
                    return;
                }
                OrderTicketBean.DataBean orderTicketBean = new OrderTicketBean.DataBean();
                orderTicketBean.setDeviceName("天津睿科");
                orderTicketBean.setPhoneNumber("13800000831");
                orderTicketBean.setPayTime("2021年07月26日");
                orderTicketBean.setOrderId("2021072310462720572625");

                List<OrderTicketBean.DataBean.ProductBeansBean> productBeans = new ArrayList<>();
                OrderTicketBean.DataBean.ProductBeansBean productBean1 = new OrderTicketBean.DataBean.ProductBeansBean();
                productBean1.setProductName("感冒灵（999）");
                productBean1.setSpecification("15/盒");
                productBean1.setUnitPrice(15);
                productBean1.setNumber(1);
                productBean1.setSubtotal(15.00);
                productBeans.add(productBean1);
                OrderTicketBean.DataBean.ProductBeansBean productBean2 = new OrderTicketBean.DataBean.ProductBeansBean();
                productBean2.setProductName("感冒清热颗粒");
                productBean2.setSpecification("5.70/盒");
                productBean2.setUnitPrice(5.70);
                productBean2.setNumber(1);
                productBean2.setSubtotal(7.50);
                productBeans.add(productBean2);

                orderTicketBean.setProductBeans(productBeans);
                orderTicketBean.setTotalPay(22.50);
                orderTicketBean.setCash(22.50);
                orderTicketBean.setMedicalInsurance(0);
                orderTicketBean.setActualTotalPay(20.50);
                orderTicketBean.setIsPrintExhort(true);
                List<OrderTicketBean.DataBean.ExhortBeansBean> exhortBeans = new ArrayList<>();
                OrderTicketBean.DataBean.ExhortBeansBean exhortBean1 = new OrderTicketBean.DataBean.ExhortBeansBean();
                exhortBean1.setProductName("感冒灵（999）");
                exhortBean1.setDescribe("开水冲服。一次10克(1袋)，一日3次。严重肝肾功能不全者禁用。");
                exhortBeans.add(exhortBean1);
                OrderTicketBean.DataBean.ExhortBeansBean exhortBean2 = new OrderTicketBean.DataBean.ExhortBeansBean();
                exhortBean2.setProductName("感冒清热颗粒");
                exhortBean2.setDescribe("开水冲服。一次1袋，一日2次，对本品过敏者禁用。严重肝肾功能不全者禁用。");
                exhortBeans.add(exhortBean2);
                orderTicketBean.setExhortBeans(exhortBeans);
                orderTicketBean.setIsPrintQrCode(true);
                orderTicketBean.setQrcode("{\"order_id\":\"2021080511310400028834\"}");
                orderTicketBean.setQrcodeDescribe("扫描二维码申请开票");
                // 打印属于耗时操作，在异步线程完成
                new Thread() {
                    @Override
                    public void run() {
                        PrinterOperateUtils.getInstance().printOrder(getResources(), orderTicketBean);
                    }
                }.start();
            }
        }.start();

    }


    @Override
    public void onEventBusResult(MsgEventBus event) {
        super.onEventBusResult(event);
        if (event.getType().equals("扫码code")) {
            btQrcodeText.setText("反扫信息==" + event.getMessage());
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        PrinterOperateUtils.getInstance().unConnectUsbPrinter();
    }

    /**
     * 设置购买数量
     *
     * @param count
     */
    public void setCount(String count) {
        ShopApiHttp.set_mch_max_sale_count(count, new ApiListener() {
            @Override
            public void onRequestStart(String requestUrl, int requestId) {

            }

            @Override
            public void onRequestComplete(String requestUrl, int requestId) {

            }

            @Override
            public void onSuccess(String requestUrl, JSONObject requestJson, int requestId) {
                SharedUtils.getInstance().putInt(ShareKey.PURCHASE_COUNT, Integer.parseInt(count)); // 购买数量
            }

            @Override
            public void onError(String requestUrl, String errorMsg, String resultData, int requestId) {

            }
        });
    }


}
